package Homework03;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 本周作业：（必做）思考有多少种方式，在main函数启动一个新线程或线程池，
 * 异步运行一个方法，拿到这个方法的返回值后，退出主线程
 */
public class Answer1_5 {
    public static void main(String[] args) throws InterruptedException {
        AtomicInteger result = new AtomicInteger();
        long start = System.currentTimeMillis();
        ExecutorService exec = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(1);
        exec.execute(() -> {
            try {
                semaphore.acquire(1);
                int sum = sum();
                result.set(sum);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                semaphore.release(1);
            }
        });
        exec.execute(() -> {
            try {
                semaphore.acquire(1);
                // 确保  拿到result 并输出
                System.out.println("异步计算结果为：" + result);
                System.out.println("使用时间：" + (System.currentTimeMillis() - start) + " ms");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                semaphore.release(1);
            }
        });

    }

    private static int sum() throws InterruptedException {
        return fibo(36);
    }

    private static int fibo(int a) {
        if (a < 2)
            return 1;
        return fibo(a - 1) + fibo(a - 2);
    }
}
